<template>
  <div class="device-manager">
    <!-- 页面标题和统计信息 -->
    <div class="page-header">
      <h2>设备管理</h2>
      <div class="device-stats">
        <el-tooltip content="系统中的设备总数" placement="top">
          <div class="stat-item">
            <el-icon><Monitor /></el-icon>
            <span class="stat-label">总设备</span>
            <span class="stat-value">{{ deviceList.length }}</span>
          </div>
        </el-tooltip>
        <el-tooltip content="当前在线的设备数量" placement="top">
          <div class="stat-item">
            <el-icon color="#67C23A"><CircleCheck /></el-icon>
            <span class="stat-label">在线</span>
            <span class="stat-value success">{{ onlineCount }}</span>
          </div>
        </el-tooltip>
        <el-tooltip content="当前离线的设备数量" placement="top">
          <div class="stat-item">
            <el-icon color="#F56C6C"><CircleClose /></el-icon>
            <span class="stat-label">离线</span>
            <span class="stat-value danger">{{ offlineCount }}</span>
          </div>
        </el-tooltip>
      </div>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="header-actions">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索设备名称或类型..."
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="设备状态" class="status-filter">
          <el-option label="全部设备" value="all" />
          <el-option label="在线设备" value="online" />
          <el-option label="离线设备" value="offline" />
        </el-select>
      </div>
      <div class="action-buttons">
        <el-button type="warning" @click="clearCurrentDevice" :icon="Close" :disabled="!currentDevice">取消设备选中</el-button>
        <el-button type="primary" v-if="hasPermission" @click="showAddDialog = true" :icon="Plus">添加设备</el-button>
      </div>
    </div>

    <!-- 设备卡片列表 -->
    <div class="device-cards" v-loading="loading">
      <div v-for="device in filteredDevices" :key="device.id" 
           :class="['device-card', { 'current-device': device.id === currentDevice?.id }]">
        <div class="device-card-header">
          <div class="device-icon" :class="{ 'current-icon': device.id === currentDevice?.id }">
            <el-icon><Monitor /></el-icon>
          </div>
          <div class="device-info">
            <div class="info-row">
              <div class="info-content">
                <h3>{{ device.device_name }}</h3>
                <p class="device-type">{{ device.device_type }}</p>
              </div>
              <div class="edit-actions" v-if="hasPermission">
                <template v-if="device.isEditing">
                  <el-button type="primary" size="small" @click="handleSave(device)" class="action-btn" circle>
                    <el-icon><Check /></el-icon>
                  </el-button>
                  <el-button size="small" @click="handleCancel(device)" class="action-btn" circle>
                    <el-icon><Close /></el-icon>
                  </el-button>
                </template>
                <el-button v-else type="primary" size="small" class="edit-btn" @click="startEdit(device)" circle>
                  <el-icon><Edit /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
          <el-tag 
            :type="device.auth === '上线' ? 'success' : 'danger'"
            size="small"
            class="status-tag"
          >
            {{ device.auth === '上线' ? '已连接' : '未连接' }}
          </el-tag>
          <el-button
            v-if="hasPermission && !device.isEditing"
            type="primary"
            size="small"
            class="edit-btn"
            @click="startEdit(device)"
          >
            <el-icon><Edit /></el-icon>
          </el-button>
        </div>
        
        <div class="device-details">
          <div class="detail-item">
            <span class="detail-label">设备ID</span>
            <span class="detail-value">{{ device.id }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">连接状态</span>
            <el-tag size="small" :type="device.auth === '上线' ? 'success' : 'warning'">
              {{ device.auth === '上线' ? '已连接' : '未连接' }}
            </el-tag>
          </div>
          <div class="detail-item">
            <span class="detail-label">故障状态</span>
            <el-tag size="small" :type="device.faultStatus.includes('故障') ? 'danger' : 'success'">
              {{ device.faultStatus }}
            </el-tag>
          </div>

          <div class="detail-item">
            <span class="detail-label">设备编号</span>
            <span class="detail-value">{{ device.device_number }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">创建时间</span>
            <span class="detail-value">{{ formatDateTime(device.created_at) }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">更新时间</span>
            <span class="detail-value">{{ formatDateTime(device.updated_at) }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">设备描述</span>
            <div v-if="!device.isEditing" class="detail-value description">{{ device.device_description || '暂无描述' }}</div>
            <el-input
              v-else
              v-model="device.editForm.device_description"
              type="textarea"
              rows="2"
              placeholder="请输入设备描述"
              class="edit-description"
            />
          </div>
        </div>

        <div class="device-actions">
            <el-button 
              :class="['switch-btn', { 'current-switch': device.id === currentDevice?.id }]"
              @click="switchToDevice(device)"
              :loading="switchingDevice"
            >
              <el-icon><SwitchButton /></el-icon>
              {{ device.id === currentDevice?.id ? '当前设备' : '切换设备' }}
            </el-button>
            <el-button v-if="hasPermission" type="primary" size="small" class="edit-btn" @click="startEdit(device)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button v-if="hasPermission" type="danger" class="delete-btn" @click="handleDelete(device)">
              <el-icon><Delete /></el-icon>
            </el-button>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 空状态提示 -->
    <el-empty v-if="filteredDevices.length === 0" description="没有找到匹配的设备" />

    <!-- 添加设备弹窗 -->
    <el-dialog v-model="showAddDialog" title="添加设备" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="设备名称" prop="device_name">
          <el-input v-model="form.device_name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="device_type">
          <el-input v-model="form.device_type" placeholder="请输入设备类型" />
        </el-form-item>
        <el-form-item label="设备描述" prop="device_description">
          <el-input
            v-model="form.device_description"
            type="textarea"
            rows="3"
            placeholder="请输入设备描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAdd(formRef)">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑设备弹窗 -->
    <el-dialog v-model="showEditDialog" title="编辑设备" width="500px">
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="设备编号" prop="device_number">
          <el-input v-model="editForm.device_number" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备名称" prop="device_name">
          <el-input v-model="editForm.device_name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="device_type">
          <el-input v-model="editForm.device_type" placeholder="请输入设备类型" />
        </el-form-item>
        <el-form-item label="设备描述" prop="device_description">
          <el-input
            v-model="editForm.device_description"
            type="textarea"
            rows="3"
            placeholder="请输入设备描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useDeviceStore } from '../stores/deviceStore'
import { storeToRefs } from 'pinia'
import { Plus, Search, Monitor, CircleCheck, CircleClose, Edit, Delete, Check, Close, SwitchButton, Refresh, Warning, Operation, Document, Clock, Timer } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { useAuthStore } from '../store/authStore';

// 数据
const deviceList = ref([]);
const showAddDialog = ref(false);
const formRef = ref(null);
const searchKeyword = ref('');
const statusFilter = ref('all');
const loading = ref(false);
const currentDevice = ref(null);
const deviceStore = useDeviceStore();
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
});

// 获取用户权限
const authStore = useAuthStore();
const userRole = computed(() => authStore.getUserRole);
const hasPermission = computed(() => {
  return userRole.value === 'LV1' || userRole.value === 'LV2';
});

const dialogVisible = ref(false);
const isEdit = ref(false);
const currentEditDevice = ref(null);
const editForm = ref({
  device_name: '',
  device_type: '',
  device_description: '',
  device_number: ''
});
const form = ref({
  device_name: '',
  device_type: '',
  device_description: ''
});
const showEditDialog = ref(false);

const rules = {
  device_name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  device_type: [
    { required: true, message: '请输入设备类型', trigger: 'blur' }
  ],
  device_description: [
    { required: false, message: '请输入设备描述', trigger: 'blur' }
  ],
  device_number: [
    { required: true, message: '请输入设备编号', trigger: 'blur' },
    { pattern: /^\d+$/, message: '设备编号必须为数字', trigger: 'blur' }
  ]
};

// 计算属性
const filteredDevices = computed(() => {
  return deviceList.value.filter(device => {
    const matchesKeyword = device.device_name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
                          device.device_type.toLowerCase().includes(searchKeyword.value.toLowerCase());
    const matchesStatus = statusFilter.value === 'all' || 
                         (statusFilter.value === 'online' ? device.auth === '上线' : device.auth !== '上线');
    return matchesKeyword && matchesStatus;
  });
});

const onlineCount = computed(() => deviceList.value.filter(d => d.auth === '上线').length);
const offlineCount = computed(() => deviceList.value.filter(d => d.auth !== '上线').length);

// 方法
const switchingDevice = ref(false);

const clearCurrentDevice = async () => {
  try {
    if (!currentDevice.value) return;
    
    await deviceStore.setCurrentDevice(null);
    currentDevice.value = null;
    ElMessage.success('已取消设备选中');
  } catch (error) {
    console.error('取消设备选中失败:', error);
    ElMessage.error(error.message || '取消设备选中失败，请稍后重试');
  }
};

const switchToDevice = async (device) => {
  if (device.id === currentDevice.value?.id) return;
  
  try {
    switchingDevice.value = true;
    if (!device.device_name || !device.device_type) {
      throw new Error('设备信息不完整');
    }
    
    // 检查设备是否在当前用户的权限范围内
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    const userRole = localStorage.getItem('userRole') || '';
    let userDevices = [];
    
    if (userInfo.devices) {
      if (Array.isArray(userInfo.devices)) {
        userDevices = userInfo.devices;
      } else if (typeof userInfo.devices === 'string') {
        try {
          userDevices = JSON.parse(userInfo.devices);
          if (!Array.isArray(userDevices)) {
            userDevices = [userDevices];
          }
        } catch (e) {
          userDevices = [userInfo.devices];
        }
      } else {
        userDevices = [userInfo.devices];
      }
    }
    
    // 如果是LV3或LV4用户，检查是否有权限访问该设备
    if ((userRole === 'LV3' || userRole === 'LV4') && userDevices.length > 0) {
      const deviceId = String(device.id);
      const hasAccess = userDevices.some(userDeviceId => String(userDeviceId) === deviceId);
      if (!hasAccess) {
        throw new Error('您没有权限访问此设备');
      }
    }
    
    const updatedDevice = {
      ...device,
      equipment_name: device.device_name,
      equipment_type: device.device_type,
      onlineStatus: device.onlineStatus
    };
    await deviceStore.setCurrentDevice(updatedDevice);
    ElMessage.success(`已切换到设备：${device.device_name}`);
    window.location.reload();
  } catch (error) {
    console.error('设备切换失败:', error);
    ElMessage.error(error.message || '切换设备失败，请稍后重试');
  } finally {
    switchingDevice.value = false;
  }
};

const formatDateTime = (dateString) => {
  if (!dateString) return '未知';
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
};

const fetchDeviceList = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    // 获取用户信息和权限
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    const userRole = localStorage.getItem('userRole') || '';
    
    // 获取设备列表
    const response = await fetch(`https://penglink.pcwxcn.top/api/device/list?page=${pagination.value.page}&page_size=${pagination.value.pageSize}`, {
      headers: { 
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    });
    if (!response.ok) throw new Error('获取设备列表失败');
    const result = await response.json();
    
    if (result.code === 200) {
      // 更新分页信息
      pagination.value.total = result.data.total;
      pagination.value.page = result.data.page;
      pagination.value.pageSize = result.data.page_size;

      // 获取设备状态记录
      const deviceListData = result.data.list || [];
      
      // 获取最新的设备状态
      const statusResponse = await fetch('https://penglink.pcwxcn.top/api/equipment/latest', {
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      });
      
      if (!statusResponse.ok) throw new Error('获取设备状态失败');
      const statusResult = await statusResponse.json();
      
      // 创建设备状态映射
      const deviceStatusMap = {};
      const runningStatusMap = {};
      if (statusResult.code === 200) {
        statusResult.data.forEach(item => {
          deviceStatusMap[item.equipment_number] = item.auth;
          

        });
      }
      
      // 根据用户角色过滤设备列表
      let filteredDevices = result.data;
      
      // 获取用户可访问的设备列表
      let userDevices = [];
      
      // 确保userDevices是数组
      if (userInfo.devices) {
        if (Array.isArray(userInfo.devices)) {
          userDevices = userInfo.devices;
        } else if (typeof userInfo.devices === 'string') {
          // 尝试解析字符串形式的devices
          try {
            userDevices = JSON.parse(userInfo.devices);
            if (!Array.isArray(userDevices)) {
              userDevices = [userDevices]; // 如果解析后不是数组，则转为数组
            }
          } catch (e) {
            // 如果解析失败，尝试将其作为单个设备ID处理
            userDevices = [userInfo.devices];
          }
        } else {
          // 如果是其他类型，尝试转换为数组
          userDevices = [userInfo.devices];
        }
      }
      
      // 根据角色级别过滤设备
      // LV1(超级管理员)和LV2(管理员)可以查看所有设备
      // LV3(租户管理员)和LV4(设备用户)只能查看指定设备
      console.log('用户角色:', userRole);
      console.log('用户设备权限列表:', userDevices);
      console.log('过滤前设备列表数量:', deviceListData.length);
      
      if (userRole === 'LV3' || userRole === 'LV4') {
        console.log('进入LV3/LV4权限过滤逻辑');
        // 确保类型匹配，将两边都转为字符串进行比较
        // 确保deviceListData是数组类型再进行过滤
        if (Array.isArray(deviceListData)) {
          const filteredList = deviceListData.filter(device => {
            const deviceId = String(device.id);
            console.log('检查设备权限:', deviceId, '设备名称:', device.device_name);
            const hasAccess = userDevices.some(userDeviceId => {
              const userDevId = String(userDeviceId);
              const match = userDevId === deviceId;
              console.log('  比较:', userDevId, '===', deviceId, '结果:', match);
              return match;
            });
            console.log('  设备访问权限:', hasAccess);
            return hasAccess;
          });
          
          console.log('过滤后设备列表数量:', filteredList.length);
          deviceList.value = filteredList.map(device => {
            // 使用设备列表API返回的数据
            return {
              ...device,
              onlineStatus: device.online_status || '下线',
              equipment_time: device.equipment_time,
              runningStatus: device.running_status || '未知',
              faultStatus: device.fault_status || '正常',
              auth: deviceStatusMap[device.device_number] || '下线',
              isEditing: false,
              editForm: {
                device_name: device.device_name,
                device_type: device.device_type,
                device_description: device.device_description
              }
            }
          });
        } else {
          console.error('设备列表数据不是数组类型:', deviceListData);
          deviceList.value = [];
        }
      } else {
        // 处理设备列表数据
        deviceList.value = deviceListData.map(device => {
          // 使用设备列表API返回的数据
          return {
            ...device,
            onlineStatus: device.online_status || '下线',
            equipment_time: device.equipment_time,
            faultStatus: device.fault_status || '正常',
            auth: deviceStatusMap[device.device_number] || '下线',
            isEditing: false,
            editForm: {
              device_name: device.device_name,
              device_type: device.device_type,
              device_description: device.device_description
            }
          }
        });
      }
      
      // 这段代码会覆盖前面的过滤结果，导致LV3和LV4用户也能看到所有设备
      // 注释掉这段代码，避免覆盖前面的过滤结果
      console.log('警告：检测到重复的设备列表处理逻辑，这会覆盖前面的权限过滤结果');
      console.log('过滤后的设备列表数量(被覆盖前):', deviceList.value.length);
      
      // 只有当deviceList.value为空时才执行下面的代码
      if (deviceList.value.length === 0) {
        console.log('设备列表为空，应用默认处理逻辑');
        deviceList.value = deviceListData.map(device => {
          // 使用设备列表API返回的数据
          return {
            ...device,
            onlineStatus: device.online_status || '下线',
            equipment_time: device.equipment_time,
            faultStatus: device.fault_status || '正常',
            auth: deviceStatusMap[device.device_number] || '下线',
            isEditing: false,
            editForm: {
              device_name: device.device_name,
              device_type: device.device_type,
              device_description: device.device_description
            }
          }
        });
      }
      
      console.log('最终设备列表数量:', deviceList.value.length);
      
      // 从 localStorage 恢复当前设备，但需要确保该设备在当前用户的权限范围内
      const savedDevice = localStorage.getItem('currentDevice');
      if (savedDevice) {
        const parsed = JSON.parse(savedDevice);
        // 确保保存的设备仍然存在于当前用户可访问的设备列表中
        const deviceExists = deviceList.value.some(d => d.id === parsed.id);
        if (deviceExists) {
          // 设备存在于当前用户的设备列表中，可以设置为当前设备
          currentDevice.value = parsed;
        } else {
          // 设备不在当前用户的权限范围内，清除localStorage中的记录
          console.log('保存的设备不在当前用户权限范围内，重置当前设备');
          localStorage.removeItem('currentDevice');
          currentDevice.value = null;
        }
      }
      
      // 如果没有当前设备且设备列表不为空，设置第一个设备为当前设备
      if (!currentDevice.value && deviceList.value.length > 0) {
        currentDevice.value = deviceList.value[0];
        localStorage.setItem('currentDevice', JSON.stringify(deviceList.value[0]));
        console.log('已将第一个可访问设备设置为当前设备:', deviceList.value[0].device_name);
      }
    }
  } catch (error) {
    ElMessage.error(error.message);
  } finally {
    loading.value = false;
  }
};

const handleAdd = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const token = localStorage.getItem('token');
        const deviceData = {
          ...form.value,
          // 创建设备时不设置device_number，由后端自动生成并与deviceId保持一致
          device_time: new Date().toISOString().slice(0, 19).replace('T', ' ')
        };
        const response = await fetch('https://penglink.pcwxcn.top/api/device', {
          method: 'POST',
          headers: { 
            'Authorization': `Bearer ${token}`, 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(deviceData)
        });
        if (!response.ok) throw new Error('添加设备失败');
        const result = await response.json();
        if (result.code === 200) {
          ElMessage.success('添加设备成功');
          showAddDialog.value = false;
          fetchDeviceList();
        }
      } catch (error) {
        ElMessage.error(error.message);
      }
    }
  });
};

// 分页处理方法
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  fetchDeviceList();
};

const handleCurrentChange = (val) => {
  pagination.value.page = val;
  fetchDeviceList();
};

// 开始编辑设备
const startEdit = (device) => {
  currentEditDevice.value = device;
  editForm.value = {
    device_name: device.device_name,
    device_type: device.device_type,
    device_description: device.device_description,
    device_number: device.id.toString()
  };
  showEditDialog.value = true;
};

// 保存编辑的设备信息
const handleSave = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`https://penglink.pcwxcn.top/api/device/${currentEditDevice.value.id}`, {
      method: 'PUT',
      headers: { 
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Accept': '*/*',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Host': 'penglink.pcwxcn.top',
        'Connection': 'keep-alive'
      },
      body: JSON.stringify({
        device_number: parseInt(editForm.value.device_number),
        device_name: editForm.value.device_name,
        device_type: editForm.value.device_type,
        device_description: editForm.value.device_description,
        device_time: new Date().toISOString().slice(0, 19).replace('T', ' ')
      })
    });
    if (!response.ok) {
      const errorData = await response.json().catch(() => null);
      throw new Error(errorData?.message || `更新设备失败 (${response.status})`);
    }
    const result = await response.json();
    if (result.code === 200) {
      showEditDialog.value = false;
      ElMessage.success('更新设备成功');
      fetchDeviceList();
    } else {
      throw new Error(result.message || '更新设备失败');
    }
  } catch (error) {
    console.error('更新设备错误:', error);
    ElMessage.error(error.message || '更新设备失败，请重试');
  }
};

// 取消编辑
const handleCancel = () => {
  showEditDialog.value = false;
  currentEditDevice.value = null;
  editForm.value = {
    device_name: '',
    device_type: '',
    device_description: ''
  };
};

const handleDelete = (device) => {
  ElMessageBox.confirm(`确认删除设备 ${device.device_name}？`, '删除设备', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`https://penglink.pcwxcn.top/api/device/${device.id}`, {
        method: 'DELETE',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      });
      if (!response.ok) throw new Error('删除设备失败');
      const result = await response.json();
      if (result.code === 200) {
        ElMessage.success('删除设备成功');
        // 如果删除的是当前设备，清除 localStorage
        if (device.id === currentDevice.value?.id) {
          localStorage.removeItem('currentDevice');
          currentDevice.value = null;
        }
        fetchDeviceList();
      }
    } catch (error) {
      ElMessage.error(error.message);
    }
  }).catch(() => {});
};

// 生命周期
let statusRefreshInterval;

onMounted(() => {
  // 检查当前用户信息和设备权限
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  const userRole = localStorage.getItem('userRole') || '';
  
  // 如果是设备用户(LV4)，检查localStorage中的currentDevice是否属于当前用户
  if (userRole === 'LV4') {
    const savedDevice = localStorage.getItem('currentDevice');
    if (savedDevice) {
      const parsed = JSON.parse(savedDevice);
      let userDevices = [];
      
      if (userInfo.devices) {
        if (Array.isArray(userInfo.devices)) {
          userDevices = userInfo.devices;
        } else if (typeof userInfo.devices === 'string') {
          try {
            userDevices = JSON.parse(userInfo.devices);
            if (!Array.isArray(userDevices)) {
              userDevices = [userDevices];
            }
          } catch (e) {
            userDevices = [userInfo.devices];
          }
        } else {
          userDevices = [userInfo.devices];
        }
      }
      
      // 检查保存的设备是否在当前用户的权限范围内
      const deviceId = String(parsed.id);
      const hasAccess = userDevices.some(userDeviceId => String(userDeviceId) === deviceId);
      
      if (!hasAccess) {
        console.log('保存的设备不在当前用户权限范围内，重置当前设备');
        localStorage.removeItem('currentDevice');
      }
    }
  }
  
  // 加载设备列表
  fetchDeviceList();
  
  // 增加刷新间隔时间，从2分钟改为5分钟，进一步减少API请求频率
  statusRefreshInterval = setInterval(fetchDeviceList, 300000);
});

onUnmounted(() => {
  // 清除定时器
  if (statusRefreshInterval) {
    clearInterval(statusRefreshInterval);
  }
});
</script>

<style scoped>
.device-manager {
  padding: 24px;
  background-color: var(--el-bg-color-page);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.page-header {
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1),
              0 4px 6px -2px rgba(0, 0, 0, 0.05);
  color: white;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 24px;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
}

.device-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  flex: 1;
  padding: 12px 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  backdrop-filter: blur(4px);
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
  background: rgba(255, 255, 255, 0.2);
}

.info-row {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  width: 100%;
  gap: 16px;
}

.info-content {
  flex: 1;
  transition: all 0.3s ease;
}

.info-edit {
  flex: 1;
  transition: all 0.3s ease;
  width: 100%;
  max-width: 300px;
  margin: 0 auto;
  padding: 16px;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.info-edit .el-input {
  margin-bottom: 16px;
  width: 100%;
}

.info-edit .el-input :deep(.el-input__wrapper) {
  width: 100%;
  padding: 10px 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  background: rgba(255, 255, 255, 0.98);
  border-radius: 8px;
}

.edit-description {
  width: 100%;
  margin-top: 12px;
}

.edit-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 12px;
  border-top: 1px solid rgba(255, 255, 255, 0.15);
}

.action-btn {
  transition: all 0.2s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.edit-btn {
  opacity: 0.8;
  transition: all 0.2s ease;
}

.edit-btn:hover {
  opacity: 1;
  transform: translateY(-1px);
}

.device-card:hover .edit-btn {
  opacity: 1;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat-label {
  color: rgba(255, 255, 255, 0.85);
  font-size: 14px;
}

.stat-value {
  font-weight: 600;
  font-size: 20px;
  color: white;
}

.stat-value.success {
  color: #52c41a;
  text-shadow: 0 0 8px rgba(82, 196, 26, 0.3);
}

.stat-value.danger {
  color: #ff4d4f;
  text-shadow: 0 0 8px rgba(255, 77, 79, 0.3);
}

.header-actions {
  margin-top: 20px;
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-area {
  display: flex;
  gap: 12px;
  flex: 1;
}

.search-input {
  width: 300px;
}

.search-input :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  box-shadow: none;
}

.search-input :deep(.el-input__inner) {
  color: white;
}

.search-input :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

.search-input :deep(.el-input__prefix-inner) {
  color: rgba(255, 255, 255, 0.6);
}

.status-filter {
  width: 160px;
}

.status-filter :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  box-shadow: none;
}

.status-filter :deep(.el-input__inner) {
  color: white;
}

.device-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(213px, 1fr));
  gap: 16px;
  padding: 16px;
  perspective: 1000px;
}

.device-card {
  background: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 10px 30px -15px rgba(0, 0, 0, 0.2),
              0 4px 6px -2px rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid transparent;
  transform-style: preserve-3d;
  transform: perspective(1000px) rotateX(0deg) rotateY(0deg);
  backface-visibility: hidden;
}

.device-card:hover {
  transform: perspective(1000px) rotateX(2deg) rotateY(2deg) translateY(-3px);
  box-shadow: 0 15px 30px -15px rgba(0, 0, 0, 0.3),
              0 6px 10px -4px rgba(0, 0, 0, 0.08);
}

.device-card.current-device {
  border-color: #52c41a;
  background: linear-gradient(to bottom, rgba(82, 196, 26, 0.05), transparent);
  box-shadow: 0 12px 25px -12px rgba(82, 196, 26, 0.3),
              0 4px 12px rgba(0, 0, 0, 0.08);
}

.device-card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.device-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  transform: translateZ(8px);
}

.device-icon .el-icon {
  font-size: 18px;
  color: white;
}

.device-info h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  transform: translateZ(5px);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.device-type {
  margin: 2px 0 0;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.device-details {
  padding: 10px 0;
  border-top: 1px solid var(--el-border-color-lighter);
  border-bottom: 1px solid var(--el-border-color-lighter);
  margin-bottom: 12px;
  transform: translateZ(5px);
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 12px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: var(--el-text-color-secondary);
  flex-shrink: 0;
  width: 50px;
}

.detail-value {
  color: var(--el-text-color-primary);
  font-weight: 500;
  flex: 1;
  text-align: right;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.device-actions {
  display: flex;
  gap: 6px;
  transform: translateZ(8px);
}

.edit-btn {
  position: absolute;
  right: 8px;
  top: 8px;
  padding: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.device-card:hover .edit-btn {
  opacity: 1;
}

.edit-description {
  margin-top: 4px;
}

.mt-2 {
  margin-top: 8px;
}

.switch-btn {
  flex: 1;
  height: 28px;
  font-size: 12px;
  font-weight: 500;
  color: white;
  border: none;
  transition: all 0.3s ease;
  border-radius: 6px;
  padding: 0 8px;
}

.switch-btn:not(.current-switch) {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  box-shadow: 0 3px 8px -2px rgba(24, 144, 255, 0.3);
}

.switch-btn:not(.current-switch):hover {
  background: linear-gradient(135deg, #096dd9 0%, #1890ff 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px -3px rgba(24, 144, 255, 0.4);
}

.current-switch {
  background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  box-shadow: 0 3px 8px -2px rgba(82, 196, 26, 0.3);
  cursor: default;
}

.delete-btn {
  width: 28px;
  height: 28px;
  padding: 0;
  border: none;
  background: linear-gradient(135deg, #ff4d4f 0%, #cf1322 100%);
  box-shadow: 0 3px 8px -2px rgba(255, 77, 79, 0.3);
  border-radius: 6px;
}

.delete-btn:hover {
  background: linear-gradient(135deg, #cf1322 0%, #ff4d4f 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px -3px rgba(255, 77, 79, 0.4);
}

.delete-btn .el-icon {
  font-size: 14px;
}

@media (max-width: 768px) {
  .device-cards {
    grid-template-columns: repeat(2, 1fr);
    padding: 12px;
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .device-cards {
    grid-template-columns: 1fr;
  }
}
</style>